#include <stdio.h>  
#include <signal.h>

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN  
#include <windows.h>  
#include <winsock2.h>  
#endif

#include <event2/thread.h>
#include <zsystem/service/httpserver/httpserver.h>
#include <zsystem/core/threading/thread.h>
#include <zsystem/core/common/logdump.h>

#ifdef __WIN32__
#define REMOTE_HOST "192.168.2.135"
#define REMOTE_PORT 8080
#define BIND_ADDRESS "0.0.0.0"
#define BIND_PORT 8080
#define THREAD_NUMBER 2
#define BACKLOG 100
#else
#define REMOTE_HOST "192.168.2.112"
#define REMOTE_PORT 8080
#define BIND_ADDRESS "0.0.0.0"
#define BIND_PORT 8080
#define THREAD_NUMBER 2
#define BACKLOG 100
#endif

void proxy(zsystem::Z_EV_REQ* req)
{
  struct evhttp_connection *evcon = NULL;
}

void 
callback(zsystem::Z_EV_REQ* req, Z_PTR arg)
{
#if USE_EVHTP
  Z_DUMP("callback( method: " << req->method << ", status: " << req->status << ")");
#else
  Z_DUMP("callback( method: " << evhttp_request_get_command(req) << ", status: " << evhttp_request_get_response_code(req) << ")");
#endif
  //struct evbuffer *buf = evhttp_request_get_input_buffer(req);
  //size_t b_sz = evbuffer_get_length(buf);
  //zsystem::httpRequestUtil::reply(req, 200, (const char*)evbuffer_pullup(buf, b_sz));
//  zsystem::ssleep(10000);
  zsystem::httpRequestUtil::reply(req, 200, "0123456789");
}

Z_BOOL g_exit=Z_FALSE;
void
sigint(int s) {
  g_exit = true;
}

int
main(int argc, char ** argv)
{
  google::InitGoogleLogging(argv[0]);

#ifdef WIN32
  google::SetLogDestination(INFO, "..\\..\\..\\logs\\httpserver_INFO_");
  google::SetLogDestination(WARNING, "..\\..\\..\\logs\\httpserver_WARNING_");
  google::SetLogDestination(ERROR, "..\\..\\..\\logs\\httpserver_ERROR_");

  WSADATA wsaData;  
  DWORD Ret;  
  if ((Ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)  {  
    printf("WSAStartup failed with error %d\n", Ret);  
    return -1;  
  }
  CHECK_EQ(evthread_use_windows_threads(), 0);
#else
  google::SetLogDestination(INFO, "/tmp/httpserver_INFO_");
  google::SetLogDestination(WARNING, "/tmp/httpserver_WARNING_");
  google::SetLogDestination(ERROR, "/tmp/httpserver_ERROR_");

//#define BIND_ADDRESS "unix:/tmp/httpServer_unittest.sock"
  CHECK_EQ(evthread_use_pthreads(), 0);
#endif

  zsystem::httpServerM* server = Z_NEW(zsystem::httpServerM)(BIND_ADDRESS, BIND_PORT, THREAD_NUMBER, BACKLOG);
  server->setCallback("", callback, server);
  server->start();
  
  signal(SIGINT, sigint);
  while(!g_exit)
  {
    zsystem::ssleep(5);
  };
  Z_DUMP("to stop server");
  server->stop();
  Z_DUMP("after stop server");

  Z_DUMP("to delete server");
  Z_SAFE_DELETE(server, ~httpServer);
  Z_DUMP("after delete server");
#ifdef WIN32
  WSACleanup();  
#endif
  return 0;  
}

